package com.uni.exp6.service;

import com.uni.exp6.dao.AccountMapper;
import com.uni.exp6.dao.BookMapper;
import com.uni.exp6.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/1/22 16:38
 **/
@Service
public class BookShopServiceImpl implements BookShopService{
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private BookShopService bookShopService;
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public int purchase(String accountName, String isbn) {
        Float price = bookMapper.queryBookPriceByIsbn(isbn);
        int stock = bookMapper.queryStockByIsbn(isbn);
        if(stock == 0) {
            throw new RuntimeException("库存不足");
        }

        bookMapper.updateBookStock(isbn);

        Account account = accountMapper.queryBalanceByAccountName(accountName);
        Float balance = account.getBalance();
        if(balance - price < 0) {
            throw new RuntimeException("余额不足!");
        }
        System.out.println(accountName +" 用户购买 " + isbn + " 成功!");
        accountMapper.updateAccount(accountName, price);
        return 1;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void checkOut1() {
        bookShopService.purchase("小明", "1001");
        bookShopService.purchase("小明", "1001");
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public void checkOut2() {
        bookShopService.purchase("小明", "1001");
        bookShopService.purchase("小明", "1001");
    }
}
